package com.rupeng.web.controller;

import java.util.*;

import javax.servlet.http.HttpServletRequest;

import com.rupeng.util.JedisUtils;
import com.rupeng.util.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageInfo;
import com.rupeng.pojo.Card;
import com.rupeng.pojo.Chapter;
import com.rupeng.pojo.Classes;
import com.rupeng.pojo.Question;
import com.rupeng.pojo.QuestionAnswer;
import com.rupeng.pojo.Segment;
import com.rupeng.pojo.User;
import com.rupeng.pojo.UserSegment;
import com.rupeng.service.CardService;
import com.rupeng.service.ChapterService;
import com.rupeng.service.ClassesUserService;
import com.rupeng.service.QuestionAnswerService;
import com.rupeng.service.QuestionService;
import com.rupeng.service.SegmentService;
import com.rupeng.service.UserCardService;
import com.rupeng.service.UserSegmentService;
import com.rupeng.service.UserService;
import com.rupeng.util.AjaxResult;
import com.rupeng.util.CommonUtils;

@Controller
@RequestMapping("/question")
public class QuestionController {
	@Autowired
	private QuestionService questionService;
	@Autowired
	private CardService cardService;
	@Autowired
	private ChapterService chapterService;
	@Autowired
	private SegmentService segmentService;
	@Autowired
	private UserSegmentService userSegmentService;
	@Autowired
	private UserCardService userCardService;
	@Autowired
	private QuestionAnswerService questionAnswerService;
	@Autowired
	private UserService userService;
	@Autowired
	private ClassesUserService classesUserService;

	@RequestMapping(value = "/ask", method = RequestMethod.GET)
	public ModelAndView askPage(HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView("question/ask");
		User user = (User) request.getSession().getAttribute("user");
		// 当前用户最近学习的segment
		Long latestSegmentId = null;
		// 最近学习的chapterid
		Long latestChapterId = null;
		// 最近学习的学习卡id
		Long latestCardId = null;
		List<Segment> segments = null;
		List<Chapter> chapters = null;
		// 当前用户的班级所属的学科的所有的学习卡
		List<Card> cards = null;

		UserSegment userSegment = new UserSegment();
		userSegment.setUserId(user.getId());
		List<UserSegment> userSegments = userSegmentService.selectList(userSegment, "createTime desc");
		if (!CommonUtils.isEmpty(userSegments)) {
			userSegment = userSegments.get(0);
			latestSegmentId = userSegment.getSegmentId();
			cards = userCardService.selectSecondListByFirstId(user.getId());
			latestChapterId = segmentService.selectOne(latestSegmentId).getChapterId();
			Segment segment = new Segment();
			segment.setChapterId(latestChapterId);
			segments = segmentService.selectList(segment, "seqNum asc");
			latestCardId = chapterService.selectOne(latestChapterId).getCardId();
			Chapter chapter = new Chapter();
			chapter.setCardId(latestCardId);
			chapters = chapterService.selectList(chapter, "seqNum asc");
		} else {
			cards = userCardService.selectSecondListByFirstId(user.getId());
			Card card = cards.get(0);
			latestCardId = card.getId();
			Chapter chapter = new Chapter();
			chapter.setCardId(card.getId());
			chapters = chapterService.selectList(chapter, "seqNum asc");
			latestChapterId = chapters.get(0).getId();
			Segment segment = new Segment();
			segment.setChapterId(latestChapterId);
			segments = segmentService.selectList(segment, "seqNum asc");
			latestSegmentId = segments.get(0).getId();
		}
		modelAndView.addObject("segments", segments);
		modelAndView.addObject("segmentId", latestSegmentId);
		modelAndView.addObject("chapters", chapters);
		modelAndView.addObject("chapterId", latestChapterId);
		modelAndView.addObject("cards", cards);
		modelAndView.addObject("cardId", latestCardId);
		return modelAndView;
	}

	@RequestMapping(value = "/ask", method = RequestMethod.POST)
	public @ResponseBody AjaxResult askSubmit(Long segmentId, String errorInfo, String errorCode, String description,
			HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("user");
		if (CommonUtils.isEmpty(description) && CommonUtils.isEmpty(errorCode) && CommonUtils.isEmpty(errorInfo)) {
			return AjaxResult.errorInstance("报错信息、相关代码、问题描述不能全为空");
		}
		Question question = new Question();
		if (segmentId != null) {
			Segment segment = segmentService.selectOne(segmentId);
			Chapter chapter = chapterService.selectOne(segment.getChapterId());
			Card card = cardService.selectOne(chapter.getCardId());

			StringBuilder builder = new StringBuilder();
			builder.append(card.getName()).append(" >> ");
			builder.append(chapter.getSeqNum()).append(" ");
			builder.append(chapter.getName()).append(" >> ");
			builder.append(segment.getSeqNum()).append(" ");
			builder.append(segment.getName());

			question.setCourseInfo(builder.toString());
		}
		question.setCreateTime(new Date());
		question.setDescription(description);
		question.setErrorCode(errorCode);
		question.setErrorInfo(errorInfo);
		question.setSegmentId(segmentId);
		question.setUserId(user.getId());
		question.setUsername(user.getName());
		questionService.insert(question);
		question = new Question();
		question.setUserId(user.getId());
		question = questionService.page(1, 1, question, "createTime desc").getList().get(0);
		Map<String, Object> notification = new HashMap<String, Object>();
		notification.put("questionId", question.getId());
		notification.put("content", user.getName()+"同学提问了新的问题，待回复");
		//保存到redis服务器，key设计为notification_{teacherId}
		Classes classes = classesUserService.selectFirstOneBySecondId(user.getId());
		List<User> users = classesUserService.selectSecondListByFirstId(classes.getId());
		for (User user2 : users){
			if (user2.getIsTeacher()!=null && user2.getIsTeacher()){
				JedisUtils.sadd("notification_"+user2.getId(), JsonUtils.toJson(notification));
			}
		}
		return AjaxResult.successInstance("提交问题成功");
	}

	@RequestMapping(value = "changeChapter.do", method = RequestMethod.POST)
	public @ResponseBody AjaxResult changeChapter(Long chapterId) {
		Segment segment = new Segment();
		segment.setChapterId(chapterId);
		List<Segment> segments = segmentService.selectList(segment, "seqNum asc");
		return AjaxResult.successInstance(segments);
	}

	@RequestMapping(value = "changeCard.do", method = RequestMethod.POST)
	public @ResponseBody AjaxResult changeCard(Long cardId) {
		Chapter chapter = new Chapter();
		chapter.setCardId(cardId);
		List<Chapter> chapters = chapterService.selectList(chapter, "seqNum asc");
		return AjaxResult.successInstance(chapters);
	}
	
	@RequestMapping(value="list.do", method=RequestMethod.GET)
	public ModelAndView list(String condition, Integer pageNum, HttpServletRequest request) {
		if (CommonUtils.isEmpty(condition)) {
			condition = "myAsked";
		}
		if (pageNum==null) {
			pageNum = 1;
		}
		ModelAndView modelAndView = new ModelAndView("question/list");
		modelAndView.addObject("condition", condition);
		PageInfo<Question> pageInfo = null;
		Question question = new Question();
		User user = (User)request.getSession().getAttribute("user");
		if (condition.equals("myAsked")) {
			question.setUserId(user.getId());
			pageInfo = questionService.page(pageNum, 10, question, "isResolved asc, createTime desc");
		} else if (condition.equals("allUnresolved")) {
			question.setIsResolved(false);
			pageInfo = questionService.page(pageNum, 10, question, "createTime desc");
		} else if (condition.equals("allResolved")) {
			question.setIsResolved(true);
			pageInfo = questionService.page(pageNum, 10, question, "createTime desc");
		} else if (condition.equals("myAnswered")) {
			List<Question> questions = questionService.selectReplyQuestionByUserId(user.getId());
			modelAndView.addObject("questions", questions);
			return modelAndView;
		}
		modelAndView.addObject("pageInfo", pageInfo);
		return modelAndView;
	}
	
	@RequestMapping(value="detail",method=RequestMethod.GET)
	public ModelAndView detailPage(Long id) {
		ModelAndView modelAndView = new ModelAndView("question/detail");
		Question question = questionService.selectOne(id);
		Long userId = question.getUserId();
		List<Classes> classesList = classesUserService.selectFirstListBySecondId(userId);
		String classesName = "";
		for (Classes classes : classesList) {
			classesName = classesName+" | "+classes.getName();
		}
		classesName = classesName.substring(3);
		modelAndView.addObject("question", question);
		modelAndView.addObject("classesName", classesName);
		//处理和此问题相关的所有答案，使得答案之间有层级关系
		//1 先找到所有的顶层答案（parentId==null）
		QuestionAnswer questionAnswer = new QuestionAnswer();
		questionAnswer.setQuestionId(question.getId());
		List<QuestionAnswer> allAnswers = questionAnswerService.selectList(questionAnswer, "createTime desc");
		if (CommonUtils.isEmpty(allAnswers)) {
			return modelAndView;
		}
		List<QuestionAnswer> rootAnswers = new ArrayList<QuestionAnswer>();
		for (QuestionAnswer answer:allAnswers) {
			if (answer.getParentId()==null) {
				rootAnswers.add(answer);
			}
		}
		for (int i=0; i<rootAnswers.size(); i++){
			QuestionAnswer questionAnswerTemp = new QuestionAnswer();
			questionAnswerTemp.setParentId(rootAnswers.get(i).getId());
			rootAnswers.get(i).setChildQuestionAnswerList(questionAnswerService.selectList(questionAnswerTemp));
		}
		modelAndView.addObject("rootAnswers", rootAnswers);
		return modelAndView;
	}
	@RequestMapping(value="answer.do",method=RequestMethod.POST)
	public ModelAndView answer(Long questionId, Long parentId, String content, HttpServletRequest request){
		User user = (User)request.getSession().getAttribute("user");
		QuestionAnswer questionAnswer = new QuestionAnswer();
		questionAnswer.setQuestionId(questionId);
		List<QuestionAnswer> oldQuestionAnswers = questionAnswerService.selectList(questionAnswer);
		questionAnswer.setContent(content);
		questionAnswer.setUserId(user.getId());
		questionAnswer.setUsername(user.getName());
		questionAnswer.setIsAdopted(false);
		questionAnswer.setCreateTime(new Date());
		if (parentId!=null) {
		    questionAnswer.setParentId(parentId);
        }
		questionAnswerService.insert(questionAnswer);
		//添加提醒
		Question question = questionService.selectOne(questionId);
		Set<Long> userIds = new HashSet<Long>();
		for(QuestionAnswer oldQuestionAnswer: oldQuestionAnswers){
			userIds.add(oldQuestionAnswer.getUserId());
		}
		userIds.add(question.getUserId());
		userIds.remove(user.getId());
		Map<String, Object> notification = new HashMap<String, Object>();
		notification.put("questionId", questionId);
		if (user.getId()==question.getUserId()){
			notification.put("content", user.getName()+"对你参与回复的问题进行追问");
		} else {
			notification.put("content", user.getName()+"回复了"+question.getUsername()+"的问题");
		}
		//保存到redis服务器，key设计为notification_{teacherId}
		for (Long userId:userIds){
			JedisUtils.sadd("notification_"+userId,JsonUtils.toJson(notification));
		}
		return new ModelAndView("redirect:/question/detail.do?id="+questionId);
	}
	@RequestMapping(value="adopt",method=RequestMethod.POST)
	public @ResponseBody AjaxResult adopt(Long questionAnswerId, HttpServletRequest request){
	    User user = (User)request.getSession().getAttribute("user");
	    QuestionAnswer questionAnswer = questionAnswerService.selectOne(questionAnswerId);
	    Question question = questionService.selectOne(questionAnswer.getQuestionId());
	    if (user.getId()!=question.getUserId() && user.getIsTeacher()==false) {
	        return AjaxResult.errorInstance("非提问者或老师，越权操作！");
        }
        questionAnswer.setIsAdopted(true);
	    questionAnswerService.update(questionAnswer);
	    question.setIsResolved(true);
	    question.setResolvedTime(new Date());
	    questionService.update(question);
		//添加提醒
		Set<Long> userIds = new HashSet<Long>();
		questionAnswer = new QuestionAnswer();
		questionAnswer.setQuestionId(question.getId());
		List<QuestionAnswer> questionAnswers = questionAnswerService.selectList(questionAnswer);
		for(QuestionAnswer questionAnswer2: questionAnswers){
			userIds.add(questionAnswer2.getUserId());
		}
		userIds.remove(user.getId());
		Map<String, Object> notification = new HashMap<String, Object>();
		notification.put("questionId", question.getId());
		notification.put("content", "曾参与"+question.getUsername()+"的问题，现已被解决");
		//保存到redis服务器，key设计为notification_{teacherId}
		for (Long userId:userIds){
			JedisUtils.sadd("notification_"+userId,JsonUtils.toJson(notification));
		}
	    return AjaxResult.successInstance("采纳成功");
    }
}